package com.lemontree.common.utils;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @Author: YLBG-YCY-1325
 * @Description: Spring 全局获取Spring容器中的bean
 * @Date: 2017/3/30
 */
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static Logger LOG = Logger.getLogger(SpringContextUtil.class);

    public SpringContextUtil() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据spring-mvc.xml中的bean标签的id获取bean
     * @param name id
     * @return 获取的bean
     */
    public static Object getBean(String name){
        try {
            return applicationContext.getBean(name);
        }catch (Exception e){
            LOG.error("获取的bean不存在！"+e);
            throw new RuntimeException("获取的bean不存在");
        }
    }

    /**
     * 根据bean的id和返回类的类型
     * @param name spring配置文件中的bean标签的id
     * @param requireType 获取类的类型
     * @param <T> 返回类的泛型
     * @return 希望得到的类
     */
    public static <T> T getBean(String name,Class<T> requireType){
        return applicationContext.getBean(name,requireType);
    }

    /**
     * 判断是否是单例
     * @param name bean id
     * @return true：是，false:否
     */
    public static boolean isSingleton(String name){
        return applicationContext.isSingleton(name);
    }
}
